package com.example.administrator.boltshow;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lhh.ptrrv.library.PullToRefreshRecyclerView;

import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.common.util.KeyValue;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import adapter.HeadAdapter;
import adapter.ShopRecyclerAdapter;
import application.MyApplication;
import config.NetConfig;
import model.Car;
import model.ShopModel;

public class ShopActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {
    private PullToRefreshRecyclerView mRecyclerView;
    private RadioButton mRadioButton;
    private List<ShopModel.DataBean> mData;
    private ShopRecyclerAdapter mAdapter;
    private String mLinkId;
    private String mGoodId;
    private HeadAdapter mPagerAdapter;
    private List<ImageView> mImageViews;
    private ImageOptions mImageOptions;
    private ViewPager mViewPager;
    private LinearLayoutManager mLinearLayoutManager;
    private RadioGroup mRadioGroup;
    private String color = null;
    private String size = null;
    private DbManager mDbManager;
    private boolean isColor;
    private boolean isSize;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop);
        initView();
        initData();
        setData();
        setListener();
    }

    private void setListener() {
        mRadioGroup.setOnCheckedChangeListener(this);
        mAdapter.setOnClickListenerColor(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isColor = true;
                Button button = (Button) v;
                color = button.getText().toString();
                Toast.makeText(ShopActivity.this, "您选择的颜色是" + color, Toast.LENGTH_SHORT).show();
            }
        });

        mAdapter.setOnClickListenerSize(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isSize = true;
                Button button = (Button) v;
                size = button.getText().toString();
                Toast.makeText(ShopActivity.this, "你选择的尺寸大小是" + size, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setData() {
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mViewPager.setAdapter(mPagerAdapter);
        mRecyclerView.setAdapter(mAdapter);

    }

    private void initData() {
        //初始化数据库manager
        DbManager.DaoConfig config = new DbManager.DaoConfig();
        mDbManager = x.getDb(config);

        mImageOptions = new ImageOptions.Builder().setUseMemCache(true).build();
        mImageViews = new ArrayList<>();
        mPagerAdapter = new HeadAdapter(mImageViews);
        mData = new ArrayList<>();
        mAdapter = new ShopRecyclerAdapter(mData, this);
        mLinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        //获取传过来的数据
        Intent intent = getIntent();
        Bundle bundle = intent.getBundleExtra("bundle");
        mLinkId = bundle.getString("linkid");
        mGoodId = bundle.getString("goodsid");
        loadMore();
    }

    private void initView() {
        mRadioGroup = (RadioGroup) findViewById(R.id.rg_shop_container);
        mRadioButton = (RadioButton) findViewById(R.id.rb_shop_addcar);
        mRecyclerView = (PullToRefreshRecyclerView) findViewById(R.id.lv_shop_list);
        ////设置头布局
        View viewHead = LayoutInflater.from(this).inflate(R.layout.view_head_shop, null);
        mViewPager = (ViewPager) viewHead.findViewById(R.id.vp_head_shop_show);
        mRecyclerView.addHeaderView(viewHead);
    }

    public void loadMore() {
        String path = String.format(NetConfig.SHOP_URL, Integer.parseInt(mGoodId), Integer.parseInt(mLinkId));
        x.http().get(new RequestParams(path), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (result != null) {
                    Gson gson = new Gson();
                    ShopModel shopModel = gson.fromJson(result, ShopModel.class);
                    mData.add(shopModel.getData());
                    mAdapter.notifyDataSetChanged();
                    //获取头布局里面的
                    List<ShopModel.DataBean.AlbumBean> album = shopModel.getData().getAlbum();
                    for (int i = 0; i < album.size(); i++) {
                        ImageView imageView = new ImageView(ShopActivity.this);
                        x.image().bind(imageView, album.get(i).getImg1080url(), mImageOptions);

                        mImageViews.add(imageView);
                    }
                    mPagerAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        MyApplication application = (MyApplication) getApplication();
        boolean isLogin = application.getIsLogin();
        switch (checkedId) {
            case R.id.rb_shop_server:
                //连接客服
                break;
            case R.id.rb_shop_car:
                if (isLogin) {
                    startActivity(new Intent(ShopActivity.this, CarActivity.class));
                } else {
                    //去登陆
                    Toast.makeText(ShopActivity.this, "你还没有登录,请前去登录", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(ShopActivity.this, LoginActivity.class));
                }
                break;
            case R.id.rb_shop_haoping:
                if (isLogin) {

                } else {
                    //去登陆
                    Toast.makeText(ShopActivity.this, "你还没有登录,请前去登录", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(ShopActivity.this, LoginActivity.class));
                }
                break;
            case R.id.rb_shop_addcar:
                //先判断是否登录
                if (isLogin) {
                    //数据保存到数据库中
                    if (saveGoodsInfo()) {
                        Toast.makeText(ShopActivity.this, "成功加入购入车", Toast.LENGTH_SHORT).show();
                        color = null;
                        size = null;
                        Log.i("TAG", "color"+color);
                        Log.i("TAG", "size"+size);
                    } else {
                        Toast.makeText(ShopActivity.this, "加入购物车失败", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    //去登陆
                    Toast.makeText(ShopActivity.this, "你还没有登录,请前去登录", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(ShopActivity.this, LoginActivity.class));
                }
                mRadioButton.setChecked(false);
                break;
            case R.id.rb_shopbuy:
                if (isLogin) {
                    //  startActivity(new Intent(ShopActivity.this,));
                } else {
                    //去登陆
                    Toast.makeText(ShopActivity.this, "你还没有登录,请前去登录", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(ShopActivity.this, LoginActivity.class));
                }
                break;
            default:
                break;
        }
    }

    public void setColorAndSize() {
        if (!isColor) {
            color = "red";
            Log.i("TAG", "游走我了吗1");
            isColor=false;
        }
        if (!isSize) {
            size = "M";
            isSize=false;
            Log.i("TAG", "游走我了吗2");
        }
        Log.i("TAG", "游走我了吗");
    }


    //购物信息存放到数据库中
    public boolean saveGoodsInfo() {
        //先判断颜色和大小是否选择了
      //  setColorAndSize();
        //先判断颜色
        if (color != null && size != null && !TextUtils.isEmpty(color) && !TextUtils.isEmpty(size)) {
            //现获取用户名
            MyApplication application = (MyApplication) getApplication();
            String userName = application.getUserName();
            //先判断这件商品之前存放过没
            ShopModel.DataBean dataBean = mData.get(0);
            String goodName = dataBean.getName();
            //根据用户名和商品名字判断,如果之前存放过,商品数量更新加一,否则存入到数据库中
            try {
                List<Car> all = mDbManager.selector(Car.class).where("userName", "=", userName).and("goodName", "=", goodName).and("size", "=", size).and("color", "=", color).findAll();
                if (all != null && all.size() != 0) {
                    //以前存放过,只需把商品数加一
                    Car car = all.get(0);
                    int count = car.getCount();
                    KeyValue keyValue = new KeyValue("count", (count + 1));
                    int update = mDbManager.update(Car.class, WhereBuilder.b("userName", "=", userName).and("goodName", "=", goodName), keyValue);
                } else {
                    //没有存放过,开始存放
                    Car car = new Car();
                    int i = dataBean.getCrazyPrice().indexOf(".");
                    String crazyPrice = dataBean.getCrazyPrice().substring(0, i);
                    car.setPrices(crazyPrice);
                    car.setIcon(dataBean.getImg1080url());
                    car.setGoodName(dataBean.getName());
                    car.setUserName(userName);
                    car.setColor(color);
                    car.setSize(size);
                    //cutprice判空
                    String cutPrice = dataBean.getCutPrice();
                    if (TextUtils.isEmpty(cutPrice)) {
                        car.setCutPrice(0);
                    } else {
                        String cutprice = dataBean.getCutPrice().substring(1);
                        car.setCutPrice(Integer.parseInt(cutprice));
                    }
                    car.setCount(1);
                    mDbManager.save(car);
                }
                return true;
            } catch (DbException e) {
                e.printStackTrace();
            }
            return false;
        } else {
            Toast.makeText(ShopActivity.this, "请选择颜色和大小", Toast.LENGTH_SHORT).show();
            return false;
        }

    }
}
